package net.begincode.maiev.handler;

import net.begincode.maiev.common.BeginCodeConstant;
import net.begincode.maiev.common.BizException;
import net.begincode.maiev.enums.CommonResponseEnum;
import net.begincode.maiev.model.BizItem;
import net.begincode.maiev.model.MonitorGroupItem;
import net.begincode.maiev.model.MonitorItem;
import net.begincode.maiev.service.BizItemService;
import net.begincode.maiev.service.BizMonitorGroupItemService;
import net.begincode.maiev.service.MonitorGroupItemService;
import net.begincode.maiev.service.MonitorItemService;
import net.begincode.maiev.util.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Stay on 2017/4/4  20:36.
 */
@Component
public class ItemHandler {
    private static Logger logger = LoggerFactory.getLogger(ItemHandler.class);

    @Resource
    private MonitorItemService monitorItemService;
    @Resource
    private BizItemService bizItemService;
    @Resource
    private BizMonitorGroupItemService bizMonitorGroupItemService;
    @Resource
    private MonitorGroupItemService monitorGroupItemService;


    @Transactional(propagation = Propagation.REQUIRED)
    public void updateGroupItem(Integer groupId, int[] itemIds) {
        List<MonitorGroupItem> list = new ArrayList<>(itemIds.length);
        MonitorGroupItem groupItem = null;
        for (int i = 0; i < itemIds.length; i++) {
            groupItem = new MonitorGroupItem();
            groupItem.setMonitorItemId(itemIds[i]);
            groupItem.setGroupId(groupId);
            list.add(groupItem);
        }
        try {
            bizMonitorGroupItemService.insertBatchByListMonitorGroupItem(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(CommonResponseEnum.EXCEPTION);
        }
    }

    public List<BizItem> listNoInGroupItemByGroupId(Integer groupId, Integer current, Integer projectId) {
        List<BizItem> list = bizItemService.listNoInGroupItemByProGroId(projectId, groupId, current, BeginCodeConstant.PAGESIZE);
        if (ListUtils.isNull(list)) {
            throw new BizException(CommonResponseEnum.DATA_NULL);
        }
        return list;
    }

    public void deleteMonitorGroupItemByItemIdAndGroupId(Integer itemId, Integer groupId) {
        try {
            monitorGroupItemService.deleteMonitorGroupItemByItemIdAndGroupId(itemId, groupId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(CommonResponseEnum.EXCEPTION);
        }
    }

    public MonitorItem getItemById(Integer id) {
        return monitorItemService.getMonitorItemById(id);
    }


}
